package com.lace.security.jwt.controller;

import com.lace.security.jwt.LoginReq;
import com.lace.security.jwt.SecurityProperties;
import com.lace.security.jwt.auth.UserContext;
import com.lace.security.jwt.exception.LoginException;
import com.lace.security.jwt.util.JwtTokenUtil;
import javafx.fxml.LoadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
/**
 * Created by WangZX on 2018/7/14.
 */
@Service
public class AuthService {

	@Autowired
	private JwtTokenUtil tokenFactory;

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private PasswordEncoder passwordEncoder;

	public Map<String, String> login(LoginReq loginReq) {
		UserDetails user = userDetailsService.loadUserByUsername(loginReq.getUsername());
		if (user == null || !passwordEncoder.matches(loginReq.getPassword(), user.getPassword())) {
			throw new LoginException();
		}

		//封装登录用户信息
		Map<String, String> tokenMap = packageLoginUser(user);

		return tokenMap;
	}

	private Map<String, String> packageLoginUser(UserDetails user){
		//封装登录用户信息
		UserContext userContext = UserContext.create(user.getUsername(), user.getAuthorities());
		Map<String, String> tokenMap = new HashMap<>();
		tokenMap.put("token", tokenFactory.createAccessToken(userContext));
		tokenMap.put("refreshToken", tokenFactory.createRefreshToken(userContext));
		tokenMap.put("userName", userContext.getUserName());
		tokenMap.put("authority", "authority");
		return tokenMap;
	}
}
